package com.qdlc.p2p.biz.service.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.qd.p2p.sina.pay.enums.IdentityType;
import com.qdlc.p2p.biz.processor.event.TppDispatchValueEvent;
import com.qdlc.p2p.biz.service.AbstractCollectService;
import com.qdlc.p2p.common.constant.LotteryCashType;
import com.qdlc.p2p.common.constant.NotifyUrl;
import com.qdlc.p2p.common.constant.Summary;
import com.qdlc.p2p.common.constant.TradeCode;
import com.qdlc.p2p.common.core.queue.QueueHandlers;
import com.qdlc.p2p.common.util.DataUtils;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.dao.TppDao;
import com.qdlc.p2p.dal.dao.UserDao;
import com.qdlc.p2p.dal.dto.Tpp;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.model.TppTradeLogModel;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 现金兑换 代收服务类
 *
 * @author hongbinglin
 * @version 1.1.0.0
 */
@Service("lotteryCollectService")
public class LotteryCollectService extends AbstractCollectService {

    private final static String BUSINESS_NAME = "抽奖现金代收-";

    /** 抽奖类型类型 */
    private ThreadLocal<Byte> lotteryType = new ThreadLocal<Byte>();

    /** 用户ID */
    private ThreadLocal<Long> userId = new ThreadLocal<Long>();

    /** 交易金额 */
    private ThreadLocal<Double> money = new ThreadLocal<Double>();
    
    /** 自动调度标识 1:自动，0:非自动 */
    private ThreadLocal<Integer> autoDispatch = new ThreadLocal<Integer>();
    
    @Resource
    private TppDao tppDao;

    @Resource
    private UserDao userDao;

    @Override
    public String getCallBackUrl() {
        return WEB_URL.concat(NotifyUrl.CASH_LOTTERY_NOTIFY_COLLECT_URL).concat(".html");
    }

    @Override
    public String getBusinessName() {
        return BUSINESS_NAME;
    }

    @Override
    public TppTradeLog getTppTradeLog() {
        // 新浪备注
        Summary summary = lotteryType.get() == LotteryCashType.NORMAL ? Summary.CASH_LOTTERY_EXCHAGE : Summary.SCORE_LOTTERY_EXCHAGE;

        Map<String, Object> memoMap = Maps.newHashMap();
        memoMap.put("lotteryType", lotteryType.get());// 抽奖类型
        memoMap.put("userId", userId.get());// 兑现用户ID
        memoMap.put("money", money.get());// 抽奖金额
        String toTppUserCustId = UserUtils.getUserTppCustId(userId.get());

        TppTradeLog tppTradeLog = new TppTradeLog();
        tppTradeLog.setTradeType(TradeCode.C1006.toString());
        tppTradeLog.setTppUserCustId(SystemConfigHelper.getValue(SystemConfigHelper.Nid.MEMBER_EMAIL)); // 平台支付
        tppTradeLog.setIdentityType(IdentityType.EMAIL.toString());
        tppTradeLog.setToTppUserCustId(toTppUserCustId);
        tppTradeLog.setMemo((new Gson()).toJson(memoMap));
        tppTradeLog.setMoney(money.get());
        tppTradeLog.setServiceType(summary.getSummaryType());
        tppTradeLog.setAutoDispatch(StringUtil.isBlank(autoDispatch.get()) ? TppTradeLogModel.NOT_AUTO : autoDispatch.get());// 自动调度标识 1:自动，0:非自动
        return tppTradeLog;
    }

    @Override
    public void analyzePars(Object... pars) {
        if (pars.length != 3 && pars.length != 4) {
            throw new IllegalArgumentException("参数个数不正确!");
        }
        try {
            this.lotteryType.set((Byte) pars[0]); // 红包兑现ID
            this.userId.set((Long) pars[1]);
            this.money.set((Double) pars[2]);
            if (pars.length == 4) {
            	this.autoDispatch.set((Integer) pars[3]);
            }
        } catch (Exception ex) {
            throw new IllegalArgumentException("参数类型正确!");
        }
    }

    @Override
    public void tradeFinish(TppTradeLog tppTradeLog, String depositStatus, double tradeAmount) {
        super.tradeFinishForStatus(tppTradeLog, depositStatus, tradeAmount);
    }

    @Override
    public void tradeSuccess(TppTradeLog tppTradeLog, String depositStatus) {
        super.tradeSuccessForStatus(tppTradeLog, depositStatus);
    }

    @Override
    public void tradeFail(TppTradeLog tppTradeLog, String depositStatus) {
        super.tradeFailForStatus(tppTradeLog, depositStatus);
        // 回调失败
        requestOrderFail(tppTradeLog);
    }

    @Override
    public void requestOrderFail(TppTradeLog tppTradeLog) {
        // 解冻红包
        logger.error(tppTradeLog.getRemark().concat("抽奖现金兑付"));
        Map<String, Object> memoMap = DataUtils.getMemo(tppTradeLog.getMemo());
        byte lotteryType = DataUtils.toByte(memoMap.get("lotteryType")); // 红包类型
        long userId = DataUtils.toLong(memoMap.get("userId"));
        // 保存调度任务信息
        Tpp tpp = new Tpp();
        tpp.setStatus(TppModel.STATUS_FAIL);
        tpp.setRespDesc(tppTradeLog.getRemark());
        User toUser = userDao.getUserById(userId);
        tpp.setServiceType(TppModel.SIGN_LOTTERY_MONEY);
        tpp.setTppType(TppModel.SIGN_LOTTERY_MONEY);
        tpp.setTppUserCustId(tppTradeLog.getTppUserCustId());
        tpp.setToUser(toUser);
        tpp.setToTppUserCustId(toUser.getTppUserCustId());
        tpp.setMoney(tppTradeLog.getMoney());
        tpp.setOrderId(tppTradeLog.getOrderNo());
        tpp.setOrderDate(DateUtil.dateStr7(tppTradeLog.getAddTime()));
        tpp.setTradeType(tppTradeLog.getTradeType());
        tpp.setFlag(lotteryType + "");
        tpp.setAddTime(DateUtil.getNow());
        tppDao.save(tpp);
        // 调度任务交由队列处理(延时处理)
        if (tppTradeLog.getAutoDispatch() != TppTradeLogModel.IS_AUTO) {// 防止重复处理
        	TppModel tppModel = TppModel.instance(tpp);
        	TppDispatchValueEvent tppDispatchValueEvent = new TppDispatchValueEvent();
        	tppDispatchValueEvent.setTppModel(tppModel);
            QueueHandlers.put(tppDispatchValueEvent);
        }
    }
}
